﻿$(function () {
    $('.aSpinEdit').spinedit({
        minimum: 0,
        maximum: 999999999,
        step: 1,
        numberOfDecimals: 2
    });

    $('.aSpinEdit2').spinedit({
        minimum: 0,
        maximum: 999999999,
        step: 1,
        numberOfDecimals: 0
    });
    recalculate_NetAmount_Head();
    // attachAllEventHandler();
    $("img[id^='calculateIcon']").on('click', function () { 
        calculate_Qty(this.id.split('_')[1]);
    });
    $("input[id^='Qty']").on('change', function () {
        calculate_Qty(this.id.split('_')[1]);
    }); 
});

function removeAllEventHandler() {
    $("[id^='Qty'], [id^='Price'],[id^='ExcludeVatAmount'], [id^='DiscountPercent'], [id^='ExtraDiscount'], [id^='VatPercent'], [id^='VatAmount'], [id^='NetAmount']").off('change');
}

function attachAllEventHandler() {
    $("[id^='Qty'], [id^='Price']").change(function () {
        var quoId = this.id.split('_')[1];
        calculate_Qty(quoId);
    });
    $("[id^='ExcludeVatAmount'], [id^='DiscountPercent'], [id^='ExtraDiscount'], [id^='VatPercent']").change(function () {
        var quoId = this.id.split('_')[1];
        calculate_VatPercent(quoId);
    });
    $("[id^='VatAmount']").change(function () {
        var quoId = this.id.split('_')[1];
        calculate_VatAmount(quoId);
    });
    $("[id^='NetAmount']").change(function () {
        var quoId = this.id.split('_')[1];
        calculate_NetAmount(quoId);
    });
}

function showCalculatingMessage() {

    $('#Calculating').clearQueue();
    $('#Calculating').css('opacity', 1);
    $('#Calculating').show();
        $('#Calculating').fadeOut(1000);
}

function setValUi(quoId, qty, price, excludeVatAmount, discountPercent, extraDiscount, vatPercent, vatAmount, netAmount) {

    if (quoId == undefined || quoId == '') {
        alert("Quoid == null, can't set ui.");
        return;
    }

    try {
        price = parseFloat(price);
        excludeVatAmount = parseFloat(excludeVatAmount);
        discountPercent = parseFloat(discountPercent);
        extraDiscount = parseFloat(extraDiscount);
        vatPercent = parseFloat(vatPercent);
        vatAmount = parseFloat(vatAmount);
        netAmount = parseFloat(netAmount);
        qty = parseInt(qty);
    } catch (e) {
        alert('setValUi error: ' + e);
    }

    // removeAllEventHandler();

    var Qty = $("#Qty_" + quoId);
    var Price = $("#Price_" + quoId);
    var ExcludeVatAmount = $("#ExcludeVatAmount_" + quoId);
    var DiscountPercent = $("#DiscountPercent_" + quoId);
    var ExtraDiscount = $("#ExtraDiscount_" + quoId);
    var VatPercent = $("#VatPercent_" + quoId);
    var VatAmount = $("#VatAmount_" + quoId);
    var NetAmount = $("#NetAmount_" + quoId);

    Qty.val(qty);
    Price.val(price.toFixed(2));
    ExcludeVatAmount.val(excludeVatAmount.toFixed(2));
    DiscountPercent.val(discountPercent.toFixed(2));
    ExtraDiscount.val(extraDiscount.toFixed(2));
    VatPercent.val(vatPercent.toFixed(2));
    VatAmount.val(vatAmount.toFixed(2));
    NetAmount.val(netAmount.toFixed(2));
    recalculate_NetAmount_Head();

    // attachAllEventHandler();
}

// ลำดับการคำนวน [ราคาต่อหน่วย -> ราคารวม(ไม่รวม Vat) -> ส่วนลด% -> เอายอดหักลบไปคิด Vat แล้วรวมเป็น Net]
function calculate_Qty(quoId) {
    showCalculatingMessage();
    var Qty = $("#Qty_" + quoId);
    var Price = $("#Price_" + quoId);
    var ExcludeVatAmount = $("#ExcludeVatAmount_" + quoId);
    var DiscountPercent = $("#DiscountPercent_" + quoId);
    var ExtraDiscount = $("#ExtraDiscount_" + quoId);
    var VatPercent = $("#VatPercent_" + quoId);
    var VatAmount = $("#VatAmount_" + quoId);
    var NetAmount = $("#NetAmount_" + quoId);
    // คำนวน
    var excludeVatAmount = Qty.val() * Price.val();
    var discountedTotal = excludeVatAmount - (excludeVatAmount * DiscountPercent.val() / 100) - ExtraDiscount.val();
    var vatAmount = discountedTotal * (VatPercent.val() / 100);
    var netAmount = (discountedTotal + vatAmount);
     
    setValUi(quoId, Qty.val(), Price.val(), excludeVatAmount, DiscountPercent.val(),
        ExtraDiscount.val(), VatPercent.val(), vatAmount, netAmount);
}

function calculate_VatPercent(quoId) {
    showCalculatingMessage();
    var Qty = $("#Qty_" + quoId);
    var Price = $("#Price_" + quoId);
    var ExcludeVatAmount = $("#ExcludeVatAmount_" + quoId);
    var DiscountPercent = $("#DiscountPercent_" + quoId);
    var ExtraDiscount = $("#ExtraDiscount_" + quoId);
    var VatPercent = $("#VatPercent_" + quoId);
    var VatAmount = $("#VatAmount_" + quoId);
    var NetAmount = $("#NetAmount_" + quoId);
    // คำนวน
    var excludeVatAmount = ExcludeVatAmount.val();
    var discountedTotal = excludeVatAmount - (excludeVatAmount * DiscountPercent.val() / 100) - ExtraDiscount.val();
    var vatAmount = discountedTotal * VatPercent.val() / 100;
    var netAmount = discountedTotal + vatAmount;

    setValUi(quoId, Qty.val(), Price.val(), excludeVatAmount, DiscountPercent.val(),
        ExtraDiscount.val(), VatPercent.val(), vatAmount, netAmount);
}

function calculate_VatAmount(quoId) {
    showCalculatingMessage();
    var Qty = $("#Qty_" + quoId);
    var Price = $("#Price_" + quoId);
    var ExcludeVatAmount = $("#ExcludeVatAmount_" + quoId);
    var DiscountPercent = $("#DiscountPercent_" + quoId);
    var ExtraDiscount = $("#ExtraDiscount_" + quoId);
    var VatPercent = $("#VatPercent_" + quoId);
    var VatAmount = $("#VatAmount_" + quoId);
    var NetAmount = $("#NetAmount_" + quoId);
    // คำนวน
    var excludeVatAmount = ExcludeVatAmount.val();
    var discountedTotal = excludeVatAmount - (excludeVatAmount * DiscountPercent.val() / 100) - ExtraDiscount.val();
    var vatAmount = parseFloat(VatAmount.val());
    var netAmount = discountedTotal + vatAmount;

    setValUi(quoId, Qty.val(), Price.val(), excludeVatAmount, DiscountPercent.val(),
        ExtraDiscount.val(), VatPercent.val(), vatAmount, netAmount);
}

function recalculate_NetAmount_Head() {
    
    var totalNet = 0.0;
    $("[id^='NetAmount']").each(function () {
        var NetAmount = parseFloat($(this).val());
        totalNet += NetAmount;
    });
    $("[id^='netAmount']").html(totalNet.toFixed(2));
}

function calculate_NetAmount(quoId) {
    recalculate_NetAmount_Head();
    //var ExcludeVatAmount = $("#ExcludeVatAmount_" + quoId);
    //var DiscountPercent = $("#DiscountPercent_" + quoId);
    //var ExtraDiscount = $("#ExtraDiscount_" + quoId);
    //var VatPercent = $("#VatPercent_" + quoId);
    //var VatAmount = $("#VatAmount_" + quoId);
    //var NetAmount = $("#NetAmount_" + quoId);
    //var Qty = $("#Qty_" + quoId);
    //var Price = $("#Price_" + quoId);

    //var netAmount = NetAmount.val();
    //var vatAmount = VatAmount.val();
    //var discountedTotal = netAmount - vatAmount;
    //var undiscountExtra = discountedTotal - ExtraDiscount.val();
    //var undiscount = undiscountExtra - ExtraDiscount.val();
    //var qty = Qty.val();
    //var excludeVatAmount = ExcludeVatAmount.val();
    //var discountedTotal = excludeVatAmount - (excludeVatAmount * DiscountPercent.val() / 100) - ExtraDiscount.val(); 

    //setValUi(quoId, Qty.val(), Price.val(), excludeVatAmount, DiscountPercent.val(),
    //    ExtraDiscount.val(), VatPercent.val(), vatAmount, netAmount);
}

$('.date-picker').datepicker({ language: 'th-th', format: 'dd/mm/yyyy' });

$("form").not("#formsearch").submit(function (e) {
    e.preventDefault();
    var currentForm = this;
    bootbox.confirm("ท่านต้องการยืนยัน ใช่หรือไม่", function (result) {
        if (result) {

            var Date = $("#txtDispenseDate").val();
            var Parcel = $("#ddlRequestParcel option:selected").val();
            var Name = $("#txtName").val();

            if (Parcel == 0 || Date == "" || Name == "") {
                if (Parcel == 0) { $("#lblReqParcel").show(); } else { $("#lblReqParcel").hide(); }
                if (Date == "") { $("#lblDispenseDate").show(); } else { $("#lblDispenseDate").hide(); }
                if (Name == "") { $("#lblName").show(); } else { $("#lblName").hide(); }
            }
            else {
                currentForm.submit();
            }
        }
    });
});

// getJSON to รายการขอเบิก
function FetchRequestParcel() {
    var Request = $("#ddlRequestParcel").val();
    $.getJSON('@Url.Action("GetRequestParcel", "Dispense")/' + Request, null, function (data) {
        $("#txtReqBy").val(data.ReqBy);
        $("#txtWarehouse").val(data.Warehouse);
        $("#txtJobSite").val(data.JobSite);
        $("#txtProject").val(data.Project);

        $("#hdReqById").val(data.ReqById);
        $("#hdWhId").val(data.WarehouseId);
        $("#hdJobSiteId").val(data.JobSiteId);
        $("#hdProjectId").val(data.ProjectId);
        $("#hdApprovedBy").val(data.ApproveBy);
        $("#hdApprovedWhen").val(data.ApproveWhen);

    });

    // Reset TextBox
    if ($("#ddlRequestParcel option:selected").val() == 0) {
        $("#txtReqBy").val("");
        $("#txtWarehouse").val("");
        $("#txtJobSite").val("");
        $("#txtProject").val("");

        $("#hdReqById").val("");
        $("#hdWhId").val("");
        $("#hdJobSiteId").val("");
        $("#hdProjectId").val("");
    }
}